package com.zsk.service.impl;

import java.util.List;

import org.springframework.stereotype.Service;

import com.zsk.bean.TableParams;
import com.zsk.service.IServiceCodeGenService;
import com.zsk.util.FileUtil;
import com.zsk.util.MvnPrjUtil;

@Service
public class ServiceCodeGenServiceImpl implements IServiceCodeGenService {

	@Override
	public boolean genServiceCode(List<TableParams> list, String packageName, String groupId, String artifactId) {
		for (TableParams tableInfo : list) {
			genServiceItf(tableInfo, packageName, artifactId);
			genService(tableInfo, packageName, artifactId);
		}
		return true;
	}

	protected void genServiceItf(TableParams tableInfo, String packageName, String artifactId) {
		String name = "service";
		String nameExt = "Service";
		String dir = MvnPrjUtil.getWorkCodeDir(artifactId, packageName) + name;
		String tableName = tableInfo.getTableName();

		StringBuilder sb = FileUtil.readTxtFile("template/IServiceTemplate.java");
		String className = MvnPrjUtil.getClassName(tableName);
		String colName = tableInfo.getTableCol().get(0).getColName();
		colName = colName.substring(0, 1).toUpperCase() + colName.substring(1);
		String content = sb.toString()
				.replace("#1", packageName + "." + name)
				.replace("#2", packageName + ".bean.ResultBean;")
				.replace("#3", packageName + ".entity." + className + "Entity;")
				.replace("#4", packageName + ".bean.PageBean;")
				.replace("#5", "I" + className + nameExt)
				.replace("#6", className + "Entity");
		FileUtil.writeTxtFile(content, dir + "/" + "I" + className + nameExt + ".java");
	}

	protected void genService(TableParams tableInfo, String packageName, String artifactId) {
		String dir = MvnPrjUtil.getCodeDir(artifactId, packageName) + "service/impl";
		String tableName = tableInfo.getTableName();

		StringBuilder sb = FileUtil.readTxtFile("template/ServiceImplTemplate.java");
		String className = MvnPrjUtil.getClassName(tableName);
		String colName = tableInfo.getTableCol().get(0).getColName();
		colName = colName.substring(0, 1).toUpperCase() + colName.substring(1);
		String content = sb.toString()
				.replace("#1", packageName + ".service.impl")
				.replace("#2",
						packageName + ".bean.ResultBean;" + "\nimport " + packageName + ".bean.PageBean;" + "\nimport "
								+ packageName + ".util.JPAUtil;")
				.replace("#3", packageName + ".entity." + className + "Entity;")
				.replace("#4", packageName + ".repository." + className + "EntityRepository;")
				.replace("#5", packageName + ".service." + "I" + className + "Service;")
				.replace("#6", className + "ServiceImpl")
				.replace("#7", "I" + className + "Service")
				.replace("#8", className + "EntityRepository")
				.replace("#9", tableName + "Rep")
				.replace("#a", className + "Entity");

		FileUtil.writeTxtFile(content, dir + "/" + className + "ServiceImpl" + ".java");
	}

}
